package questions;

import org.junit.jupiter.api.Test;

import java.lang.ref.SoftReference;
import java.util.concurrent.TimeUnit;

public class SoftReferenceDemo {
    public static void main(String[] args) throws InterruptedException {
        testSoftReference1();
        testSoftReference2();
    }

    /**
     * 一般情况，不配置运行内存，内存充足，不GC
     */
    public static void testSoftReference1(){
        System.out.println("内存充足不回收");
        Object o=new Object();
        System.out.println(o);
        SoftReference<Object> softReference= new SoftReference<>(o);
        o=null;
        System.gc();
        System.out.println(softReference.get());
    }
    /**
     * 配置内存为10M，在过程中申请一个10M的内存大对象，让系统执行垃圾回收
     * -Xms10m -Xmx10m -XX:+PrintGCDetails
     */
    public static void testSoftReference2() throws InterruptedException {
        System.out.println("内存不充足，回收");
        Object o = new Object();
        System.out.println(o);
        SoftReference<Object> softReference = new SoftReference<>(o);
        o = null;
        try {
            byte[]arr=new byte[10*1024*1024];
        }finally {
            System.out.println(softReference.get());
        }


    }
}
